import { defineStore } from 'pinia'
import api from '../api'

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null,
    token: localStorage.getItem('token') || null
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token
  },
  
  actions: {
    async login(username, password, captcha, captchaKey) {
      try {
        const response = await api.post('/chance/auth/login', {
          username,
          password,
          captcha,
          captcha_key: captchaKey
        })
                
        this.token = response.access_token
        localStorage.setItem('token', this.token)
        
        // 设置axios默认Authorization头
        api.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
        
        return true
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },
    
    logout() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
      delete api.defaults.headers.common['Authorization']
    },
    
    async fetchUserInfo() {
      if (!this.token) return
      
      try {
        // 这里假设后端有一个获取当前用户信息的接口
        const response = await api.get('/chance/users/me')
        this.user = response
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.logout()
      }
    }
  }
})